package com.report.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.core.util.ZipUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author summer
 * @version 1.0
 * @date 2024/8/11 15:52
 */
@Configuration
@ConfigurationProperties(prefix = "oss")
@Data
@Slf4j
public class DownloadFileUtils {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
    private String accessUrl;
    private String tempFile;
    private String downloadPath;
    private String pdfPath;
    private String downloadVip;


    public void downloadOssFile(String fileName, HttpServletResponse response)  {
        BufferedInputStream input = null;
        OutputStream outputStream = null;
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        OSSObject ossObject = ossClient.getObject(bucketName,  fileName);
        try {
            response.reset();
            response.setCharacterEncoding("utf-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Content-Disposition", "attachment;filename="+fileName+" 【新研报 xinyanbao.cn】.pdf");
//            response.setHeader("Content-Disposition", "attachment; filename=" + name);
            response.setContentType("application/pdf");
            input = new BufferedInputStream(ossObject.getObjectContent());
            byte[] buffBytes = new byte[1024];
            outputStream = response.getOutputStream();
            int read = 0;
            while ((read = input.read(buffBytes)) != -1) {
                outputStream.write(buffBytes, 0, read);
            }
            outputStream.flush();
            // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
            ossObject.close();
        }catch (Exception e){

        }

    }


    public void downloadPDFFile(String fileName,String path,HttpServletResponse response1)  {
        try {
            response1.reset();
            response1.setCharacterEncoding("utf-8");
            response1.setHeader("Access-Control-Allow-Origin", "*");
            response1.setHeader("Content-Disposition", "attachment;filename="+fileName+" 【新研报 xinyanbao.cn】.pdf");
            response1.setContentType("application/pdf");
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(path);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode==200){
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    InputStream inputStream = entity.getContent();
                    OutputStream outputStream =  response1.getOutputStream();
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                    outputStream.close();
                    inputStream.close();
                }

            }
        }catch (Exception e){

        }


    }


    public void downloadOssFile(String fileName, HttpServletResponse response,String pdfName)  {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        DownloadFileRequest downloadFileRequest = new DownloadFileRequest(bucketName, fileName);
        downloadFileRequest.setDownloadFile(downloadPath + "download.pdf");
        // 设置分片大小，单位为字节，取值范围为100 KB~5 GB。默认值为100 KB。
        downloadFileRequest.setPartSize(1 * 1024 * 1024);
        // 设置分片下载的并发数，默认值为1。
        downloadFileRequest.setTaskNum(10);
        // 开启断点续传下载，默认关闭。
        downloadFileRequest.setEnableCheckpoint(true);

        try {
            DownloadFileResult downloadFileResult = ossClient.downloadFile(downloadFileRequest);
            ObjectMetadata objectMetadata = downloadFileResult.getObjectMetadata();

            downloadPDF(response,FileUtil.file(downloadPath + "download.pdf"),pdfName);
            FileUtil.del(downloadPath + "download.pdf");
        }catch (Throwable e){

        }



//        ExecutorService executorService = Executors.newFixedThreadPool(5);
//        executorService.execute(new Runnable() {
//            @Override
//            public void run() {
//                downloadPDF(response,ossObject,name);
//            }
//        });
//
//      executorService.shutdown();
//      ossClient.shutdown();

        //new DownloadTimerTask(ossObject,response).run();
    //  downloadPDF(response,ossObject);
    }

   public void removeFile(String fileName) {
        FileUtil.del(downloadVip + fileName);
   }

   public void downloadVipPdf(String path,String fileName)  {
       OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
       DownloadFileRequest downloadFileRequest = new DownloadFileRequest(bucketName, path);
       downloadFileRequest.setDownloadFile(downloadVip +fileName);
       // 设置分片大小，单位为字节，取值范围为100 KB~5 GB。默认值为100 KB。
       downloadFileRequest.setPartSize(1 * 1024 * 1024);
       // 设置分片下载的并发数，默认值为1。
       downloadFileRequest.setTaskNum(10);
       // 开启断点续传下载，默认关闭。
       downloadFileRequest.setEnableCheckpoint(true);

       try {
           DownloadFileResult downloadFileResult = ossClient.downloadFile(downloadFileRequest);
           ObjectMetadata objectMetadata = downloadFileResult.getObjectMetadata();
           log.info("objectMetadata:{}",objectMetadata);
       }catch (Throwable e){
           log.error("downloadVipPdf error:{}",e,e.getLocalizedMessage());
       }
   }


   public void downloadZip(HttpServletResponse response)  {
       ZipUtil.zip(downloadVip);
       try {
           response.reset();
           response.setContentType("application/zip");
           response.setHeader("Content-Disposition", "attachment;filename=pdf.zip");
           response.setHeader("Access-Control-Allow-Origin", "*");
           InputStream fileInputStream = new FileInputStream(FileUtil.file(pdfPath+"pdf.zip"));
           OutputStream   outputStream = response.getOutputStream();
           IOUtils.copy(fileInputStream, outputStream);
           FileUtil.del(pdfPath+"pdf.zip");
       }catch (Exception e){

       }
   }



    public void downloadPDF( HttpServletResponse response, File file,String pdfName)  {

        response.reset();
        response.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");

        response.setHeader("Content-Disposition", "attachment;filename="+pdfName+" 【新研报 xinyanbao.cn】.pdf");

//            response.setHeader("Content-Disposition", "attachment; filename=" + name);
        response.setContentType("application/pdf");
        response.setContentLengthLong(file.length());
        try ( InputStream fileInputStream = new FileInputStream(file);
            OutputStream   outputStream = response.getOutputStream();){
            IOUtils.copy(fileInputStream, outputStream);
        }catch (Exception e){

        }
    }
}
